package com.yantong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yantong.constant.*;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.ActivityProductVo;
import com.yantong.pojo.vo.CommanerVo;
import com.yantong.pojo.vo.StoreFreechargeVo;
import com.yantong.service.*;
import com.yantong.utils.DateUtil;
import com.yantong.utils.ObjectUtils;
import com.yantong.utils.PageUtils;
import com.yantong.utils.ValidateUtil;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 支付服务
 *
 * @author kanghaixin
 * @date 2018/9/29.9:50
 */
@Service
public class ActivityServiceImpl implements ActivityService {

	private static Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);

	@Autowired
	@Lazy
	private ProductCentreService productCentreService;
	@Autowired
	private TicketService ticketService;

	@Autowired
	private ActivityMapper activityMapper;
	@Autowired
	private ActivityProductSkuMapper activityProductSkuMapper;
	@Autowired
	private ActivityProductMapper activityProductMapper;
	@Autowired
	@Lazy
	ProductCommentService productCommentService;
	@Autowired
	private MemberService memberService;
	@Autowired
    StringRedisTemplate redisTemplate;
	@Autowired
	private StoreFreechargeMapper storeFreechargeMapper;
	@Autowired
	private StoreFreechargeMiddleMapper storeFreechargeMiddleMapper;
	@Autowired
	private ConfigService configService;

	@Override
	public PageUtils<Activity> listAll(int offset, int limit, ActivityParam activityParam) {
		PageUtils<Activity> pageUtils = new PageUtils<>();
		Map<String, Object> paramMap = new HashMap<>();
		if (ValidateUtil.isNotEmptyString(activityParam.getProductName())) {
			paramMap.put("activityName", activityParam.getActivityName());
		}
		if (ValidateUtil.isNotEmptyString(activityParam.getActivityName())) {
			paramMap.put("activityName", activityParam.getActivityName());
		}
		if (activityParam.getType() != null) {
			paramMap.put("type", activityParam.getType());
		}
		if (null != activityParam.getCentreId()) {
			paramMap.put("centreId", activityParam.getCentreId());
		}
		if (null != activityParam.getTeamId()) {
			paramMap.put("teamId", activityParam.getTeamId());
		}
		if (null != activityParam.getShowType()) {
			paramMap.put("showType", activityParam.getShowType());
		}
		if (null != activityParam.getStatus()) {
			paramMap.put("status", activityParam.getStatus());
		}
		paramMap.put("todayDate", DateUtil.convertDateToStr(new Date(), DateUtil.yyyy_MM_dd));
		paramMap.put("tomorrowDate", DateUtil.getAddDayDateStr(new Date(), 1));
		int total = activityMapper.queryTotal(paramMap);
		if (total > 0) {
			pageUtils.setTotal(Integer.parseInt(total + ""));
			List<Activity> list = activityMapper.pageListBycondition(paramMap, new RowBounds(offset, limit));
			pageUtils.setRows(list);
		}
		return pageUtils;
	}

	@Override
	public List<ActivityProductSku> listActivityProductSkuByProductId(Long productCentreId) {
		ActivityProductSkuExample example = new ActivityProductSkuExample();
		example.createCriteria().andProductCentreIdEqualTo(productCentreId);

		return activityProductSkuMapper.selectByExample(example);
	}

	@Override
	public Long saveActivity(ActivityParam params) {
		//活动名称
		if (ValidateUtil.isEmptyString(params.getActivityName())) {
			throw new BDException("请输入活动名称");
		}
		//活动名称
		if (params.getStartTime() == null) {
			throw new BDException("请输入开始时间");
		}
		//活动名称
		if (params.getEndTime() == null) {
			throw new BDException("请输入结束时间");
		}

//        //满赠
//        if (params.getType() == ActivityType.FULL_GIFT.getType()) {
//            //参与活动的商品
//            if (ValidateUtil.isEmptyCollection(params.getJoinProductList())) {
//                throw new BDException("请选择参与活动的商品");
//            }
//
//            if (ValidateUtil.isEmptyCollection(params.getGiftProductList())) {
//                throw new BDException("请选择参与活动的赠品");
//            }
//        }
//        //优惠套装
//        else if (params.getType() == ActivityType.PACKAGE.getType()) {
//            //优惠券打包
//            if (ActivityMode.PACKAGE_PRODUCT.getType() == params.getMode()) {
//                if (ValidateUtil.isEmptyCollection(params.getJoinProductList())) {
//                    throw new BDException("请选择套餐内的商品");
//                }
//            } else if (ActivityMode.PACKAGE_COUPON.getType() == params.getMode()) {
//                if (ValidateUtil.isEmptyCollection(params.getGiftProductList())) {
//                    throw new BDException("请选择套餐内的优惠券");
//                }
//            }
//        }

		Activity activity = new Activity();
		BeanUtils.copyProperties(params, activity);
		int insertNum = activityMapper.insertSelective(activity);

//        if (insertNum > 0) {
//            if (ValidateUtil.isNotEmptyCollection(params.getJoinProductList())) {
//                for (ActivityProduct joinProduct : params.getJoinProductList()) {
//                    joinProduct.setActivityId(activity.getId());
//                    if (params.getType() == ActivityType.FULL_GIFT.getType()) {
//                        joinProduct.setType(ActivityProductType.FULL_GIFT.getType());
//                    } else if (params.getType() == ActivityType.PACKAGE.getType()) {
//                        if (ActivityMode.PACKAGE_PRODUCT.getType() == params.getMode()) {
//                            joinProduct.setType(ActivityProductType.PACKAGE_PRODUCT.getType());
//                        } else if (ActivityMode.PACKAGE_COUPON.getType() == params.getMode()) {
//                            joinProduct.setType(ActivityProductType.PACKAGE_COUPON.getType());
//                        }
//                    }
//                    activityProductMapper.insertSelective(joinProduct);
//                }
//
//                if (ValidateUtil.isNotEmptyCollection(params.getJoinProductSkuList())) {
//                    for (ActivityProductSku joinProductSku : params.getJoinProductSkuList()) {
//                        joinProductSku.setActivityId(activity.getId());
//                        if (params.getType() == ActivityType.FULL_GIFT.getType()) {
//                            joinProductSku.setType(ActivityProductType.FULL_GIFT.getType());
//                        } else if (params.getType() == ActivityType.PACKAGE.getType()) {
//                            if (ActivityMode.PACKAGE_PRODUCT.getType() == params.getMode()) {
//                                joinProductSku.setType(ActivityProductType.PACKAGE_PRODUCT.getType());
//                            } else if (ActivityMode.PACKAGE_COUPON.getType() == params.getMode()) {
//                                joinProductSku.setType(ActivityProductType.PACKAGE_COUPON.getType());
//                            }
//                        }
//                        activityProductSkuMapper.insertSelective(joinProductSku);
//                    }
//                }
//            }
//
//            if (ValidateUtil.isNotEmptyCollection(params.getGiftProductList())) {
//                for (ActivityProduct giftProduct : params.getGiftProductList()) {
//                    giftProduct.setActivityId(activity.getId());
//                    if (params.getType() == ActivityType.FULL_GIFT.getType()) {
//                        giftProduct.setType(ActivityProductType.GIFT_PRODUCT.getType());
//                    } else if (params.getType() == ActivityType.PACKAGE.getType()) {
//                        giftProduct.setType(ActivityProductType.PACKAGE_COUPON.getType());
//                    }
//                    activityProductMapper.insertSelective(giftProduct);
//                }
//
//                if (ValidateUtil.isNotEmptyCollection(params.getGiftProductSkuList())) {
//                    for (ActivityProductSku giftProductSku : params.getGiftProductSkuList()) {
//                        giftProductSku.setActivityId(activity.getId());
//                        if (params.getType() == ActivityType.FULL_GIFT.getType()) {
//                            giftProductSku.setType(ActivityProductType.GIFT_PRODUCT.getType());
//                        }
//                        activityProductSkuMapper.insertSelective(giftProductSku);
//                    }
//                }
//            }
//        }

		return activity.getId();
	}

	@Override
	public int updateActivity(ActivityParam params) {
		if (params.getOperType() == null || params.getOperType() == 0) {
			if (ValidateUtil.isEmptyString(params.getActivityName())) {
				throw new BDException("请输入活动名称");
			}
			//活动名称
			if (params.getStartTime() == null) {
				throw new BDException("请输入开始时间");
			}
			//活动名称
			if (params.getEndTime() == null) {
				throw new BDException("请输入结束时间");
			}
		}

		//更新活动信息
		Activity activity = new Activity();
		BeanUtils.copyProperties(params, activity);
		return activityMapper.updateByPrimaryKeySelective(activity);
	}

	private void updatePackageActivity(ActivityParam params) {
		if (params.getMode() == null) {
			throw new BDException("请选择参与活动对象");
		}
		//参与活动的商品
		if (ValidateUtil.isEmptyCollection(params.getJoinProductList()) && params.getMode() == ActivityMode.PACKAGE_PRODUCT.getType()) {
			throw new BDException("请选择参与活动的商品");
		}

		if (ValidateUtil.isEmptyCollection(params.getGiftProductList()) && params.getMode() == ActivityMode.PACKAGE_COUPON.getType()) {
			throw new BDException("请选择参与活动的优惠券");
		}

		//=========优惠套餐-商品-活动的商品修改逻辑-start====================//
		//商品逻辑，判断修改商品，删除优惠券的数据
		if (params.getMode().intValue() == ActivityMode.PACKAGE_PRODUCT.getType()) {
			for (ActivityProduct activityProduct : params.getJoinProductList()) {
				//ID存在，表示要更新的记录
				if (activityProduct.getId() != null) {
					activityProductMapper.updateByPrimaryKeySelective(activityProduct);
				}
				//ID不存在，则表示要新增记录
				else {
					activityProduct.setType(ActivityProductType.PACKAGE_PRODUCT.getType());
					activityProduct.setActivityId(params.getId());
					activityProductMapper.insertSelective(activityProduct);
				}
				//删除的逻辑不需要考虑，前端直接调用删除的接口
			}
			//删除优惠券模式的产品
			ActivityProductExample example = new ActivityProductExample();
			example.createCriteria().andActivityIdEqualTo(params.getId()).andTypeEqualTo(ActivityProductType.PACKAGE_COUPON.getType());
			activityProductMapper.deleteByExample(example);

			if (ValidateUtil.isNotEmptyCollection(params.getJoinProductSkuList())) {
				for (ActivityProductSku activityProductSku : params.getJoinProductSkuList()) {
					//ID存在，表示要更新的记录
					if (activityProductSku.getId() != null) {
						activityProductSkuMapper.updateByPrimaryKeySelective(activityProductSku);
					}
					//ID不存在，则表示要新增记录
					else {
						activityProductSku.setType(ActivityProductType.PACKAGE_PRODUCT.getType());
						activityProductSku.setActivityId(params.getId());
						activityProductSkuMapper.insertSelective(activityProductSku);
					}
					//删除的逻辑不需要考虑，前端直接调用删除的接口即可
				}
			}

			//删除商品对应的SKU
			ActivityProductSkuExample activityProductSkuExample = new ActivityProductSkuExample();
			activityProductSkuExample.createCriteria().andActivityIdEqualTo(params.getId()).andTypeEqualTo(ActivityProductType.PACKAGE_COUPON.getType());
			activityProductSkuMapper.deleteByExample(activityProductSkuExample);
		}
		//=========优惠套餐-商品-活动的商品修改逻辑-end====================//

		//=========满赠活动的赠品修改逻辑-start====================//
		if (params.getMode().intValue() == ActivityMode.PACKAGE_COUPON.getType()) {
			for (ActivityProduct giftActivityProduct : params.getGiftProductList()) {
				//ID存在，表示要更新的记录
				if (giftActivityProduct.getId() != null) {
					activityProductMapper.updateByPrimaryKeySelective(giftActivityProduct);
				}
				//ID不存在，则表示要新增记录
				else {
					giftActivityProduct.setType(ActivityProductType.PACKAGE_COUPON.getType());
					giftActivityProduct.setActivityId(params.getId());
					activityProductMapper.insertSelective(giftActivityProduct);
				}
				//删除的逻辑不需要考虑，前端直接调用删除的接口
			}

			//删除优惠券模式的产品
			ActivityProductExample example = new ActivityProductExample();
			example.createCriteria().andActivityIdEqualTo(params.getId()).andTypeEqualTo(ActivityProductType.PACKAGE_PRODUCT.getType());
			activityProductMapper.deleteByExample(example);

			if (ValidateUtil.isNotEmptyCollection(params.getGiftProductSkuList())) {
				for (ActivityProductSku activityProductSku : params.getGiftProductSkuList()) {
					//ID存在，表示要更新的记录
					if (activityProductSku.getId() != null) {
						activityProductSkuMapper.updateByPrimaryKeySelective(activityProductSku);
					}
					//ID不存在，则表示要新增记录
					else {
						activityProductSku.setType(ActivityProductType.PACKAGE_COUPON.getType());
						activityProductSku.setActivityId(params.getId());
						activityProductSkuMapper.insertSelective(activityProductSku);
					}
					//删除的逻辑不需要考虑，前端直接调用删除的接口即可
				}
			}

			//删除商品对应的SKU
			ActivityProductSkuExample activityProductSkuExample = new ActivityProductSkuExample();
			activityProductSkuExample.createCriteria().andActivityIdEqualTo(params.getId()).andTypeEqualTo(ActivityProductType.PACKAGE_PRODUCT.getType());
			activityProductSkuMapper.deleteByExample(activityProductSkuExample);
		}
		//=========满赠活动的赠品修改逻辑-end====================//
	}

	private void updateFullGift(ActivityParam params) {
		//参与活动的商品
		if (ValidateUtil.isEmptyCollection(params.getJoinProductList())) {
			throw new BDException("请选择参与活动的商品");
		}

		if (ValidateUtil.isEmptyCollection(params.getGiftProductList())) {
			throw new BDException("请选择参与活动的赠品");
		}

		//=========满赠活动的商品修改逻辑-start====================//
		for (ActivityProduct activityProduct : params.getJoinProductList()) {
			//ID存在，表示要更新的记录
			if (activityProduct.getId() != null) {
				activityProductMapper.updateByPrimaryKeySelective(activityProduct);
			}
			//ID不存在，则表示要新增记录
			else {
				activityProduct.setType(ActivityProductType.FULL_GIFT.getType());
				activityProduct.setActivityId(params.getId());
				activityProductMapper.insertSelective(activityProduct);
			}
			//删除的逻辑不需要考虑，前端直接调用删除的接口
		}

		if (ValidateUtil.isNotEmptyCollection(params.getJoinProductSkuList())) {
			for (ActivityProductSku activityProductSku : params.getJoinProductSkuList()) {
				//ID存在，表示要更新的记录
				if (activityProductSku.getId() != null) {
					activityProductSkuMapper.updateByPrimaryKeySelective(activityProductSku);
				}
				//ID不存在，则表示要新增记录
				else {
					activityProductSku.setType(ActivityProductType.FULL_GIFT.getType());
					activityProductSku.setActivityId(params.getId());
					activityProductSkuMapper.insertSelective(activityProductSku);
				}
				//删除的逻辑不需要考虑，前端直接调用删除的接口即可
			}
		}
		//=========满赠活动的商品修改逻辑-end====================//

		//=========满赠活动的赠品修改逻辑-start====================//
		for (ActivityProduct giftActivityProduct : params.getGiftProductList()) {
			//ID存在，表示要更新的记录
			if (giftActivityProduct.getId() != null) {
				activityProductMapper.updateByPrimaryKeySelective(giftActivityProduct);
			}
			//ID不存在，则表示要新增记录
			else {
				giftActivityProduct.setType(ActivityProductType.GIFT_PRODUCT.getType());
				giftActivityProduct.setActivityId(params.getId());
				activityProductMapper.insertSelective(giftActivityProduct);
			}
			//删除的逻辑不需要考虑，前端直接调用删除的接口
		}

		if (ValidateUtil.isNotEmptyCollection(params.getGiftProductSkuList())) {
			for (ActivityProductSku activityProductSku : params.getGiftProductSkuList()) {
				//ID存在，表示要更新的记录
				if (activityProductSku.getId() != null) {
					activityProductSkuMapper.updateByPrimaryKeySelective(activityProductSku);
				}
				//ID不存在，则表示要新增记录
				else {
					activityProductSku.setType(ActivityProductType.GIFT_PRODUCT.getType());
					activityProductSku.setActivityId(params.getId());
					activityProductSkuMapper.insertSelective(activityProductSku);
				}
				//删除的逻辑不需要考虑，前端直接调用删除的接口即可
			}
		}
		//=========满赠活动的赠品修改逻辑-end====================//
	}

	@Override
	public Activity getActivityById(Long id) {
		return activityMapper.selectByPrimaryKey(id);
	}

	@Override
	public List<ActivityProduct> selectByExample(ActivityProductExample example) {
		return activityProductMapper.selectByExample(example);
	}

	@Override
	public List<ActivityProduct> listActivityProductsByActivityId(Long activityId, Integer type) {
		ActivityProductExample example = new ActivityProductExample();
		example.createCriteria().andActivityIdEqualTo(activityId).andTypeEqualTo(type);
		return activityProductMapper.selectByExample(example);
	}

	@Override
	public List<ActivityProductSku> listActivityProductSkusByActivityId(Long activityId, Integer type) {
		ActivityProductSkuExample example = new ActivityProductSkuExample();
		example.createCriteria().andActivityIdEqualTo(activityId).andTypeEqualTo(type);
		return activityProductSkuMapper.selectByExample(example);
	}

	@Override
	public int removeActivity(Long id) {
		//删除SKU
		ActivityProductSkuExample activityProductSkuExample = new ActivityProductSkuExample();
		activityProductSkuExample.createCriteria().andActivityIdEqualTo(id);
		activityProductSkuMapper.deleteByExample(activityProductSkuExample);
		//删除商品
		ActivityProductExample activityProductExample = new ActivityProductExample();
		activityProductExample.createCriteria().andActivityIdEqualTo(id);
		activityProductMapper.deleteByExample(activityProductExample);

		return activityMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int removeActivityProduct(Long id) {
		ActivityProduct activityProduct = activityProductMapper.selectByPrimaryKey(id);
		Activity activity = activityMapper.selectByPrimaryKey(activityProduct.getActivityId());
		if (null == activity) {
			throw new BDException("活动信息异常，请联系系统管理员");
		}

		int removeCount = activityProductMapper.deleteByPrimaryKey(id);

		//计算活动里面的商品件数
		if (activity.getType() == ActivityType.PACKAGE.getType()) {
			ActivityProductExample example = new ActivityProductExample();
			ActivityProductExample.Criteria criteria = example.createCriteria();
			criteria.andActivityIdEqualTo(activity.getId());
			if (ActivityMode.PACKAGE_PRODUCT.getType() == activity.getMode()) {
				criteria.andTypeEqualTo(ActivityProductType.PACKAGE_PRODUCT.getType());
			} else {
				criteria.andTypeEqualTo(ActivityProductType.PACKAGE_COUPON.getType());
			}

			//修改商品数量
			long productCount = activityProductMapper.countByExample(example);
			if (activity.getJoinNum() == null || activity.getJoinNum().longValue() != productCount) {
				activity.setJoinNum((int) productCount);
			}

			//修改活动的价格
			changeActivityPrice(activity, true);
		}

		return removeCount;
	}

	@Override
	public List<StoreFreechargeVo> selectAllActivityProduct(Long activityId, Integer type) {
		ActivityProductExample example = new ActivityProductExample();
		example.createCriteria().andActivityIdEqualTo(activityId).andTypeEqualTo(type);
		List<ActivityProduct> list = activityProductMapper.selectByExample(example);
		List<String> freechargeIdList = new ArrayList<>();
		list.forEach(s -> {
			if (ValidateUtil.isNotEmptyString(s.getFreechargeId())) {
				String[] strs = s.getFreechargeId().split(",");
				Collections.addAll(freechargeIdList, strs);
			}
		});
		List<StoreFreechargeVo> storeFreechargeVoList = new ArrayList<>();
		if(ValidateUtil.isNotEmptyCollection(freechargeIdList)){
			storeFreechargeVoList = storeFreechargeMapper.selectByIdIn(freechargeIdList);
		}
		return storeFreechargeVoList;
	}

	@Override
	public List<StoreFreechargeVo> selectAllActivityProductCoupon(Long activityId, Integer type) {
		ActivityProductExample example = new ActivityProductExample();
		example.createCriteria().andActivityIdEqualTo(activityId).andTypeEqualTo(type);
		List<ActivityProduct> list = activityProductMapper.selectByExample(example);
		List<String> couponIdList = new ArrayList<>();
		list.forEach(s -> {
			if (ValidateUtil.isNotEmptyString(s.getCouponIds())) {
				String[] strs = s.getCouponIds().split(",");
				Collections.addAll(couponIdList, strs);
			}
		});
		List<StoreFreechargeVo> storeFreechargeVoList = new ArrayList<>();
		if(ValidateUtil.isNotEmptyCollection(couponIdList)){
			storeFreechargeVoList = storeFreechargeMapper.selectByIdIn(couponIdList);
		}
		return storeFreechargeVoList;
	}

	/**
	 * 修改活动商品的价格
	 *
	 * @param activity 活动对象
	 */
	void changeActivityPrice(Activity activity, boolean updateActivity) {
		//修改商品的价格
		ActivityProduct activityProductPrice = activityProductMapper.selectPriceByActivityId(activity.getId());
		if (null != activityProductPrice) {
			activity.setActivityPrice(activityProductPrice.getActivityPrice());
			activity.setMaxActivityPrice(activityProductPrice.getMaxActivityPrice());
		}
		if (updateActivity) {
			activityMapper.updateByPrimaryKeySelective(activity);
		}
	}

	@Override
	public int addActivityProduct(ActivityProduct activityProduct) {
		//需要校验，添加的产品，与已经存在的产品是否同一个门店的，不是同一个门店的不能添加
		Activity activity = activityMapper.selectByPrimaryKey(activityProduct.getActivityId());
		if (null == activity) {
			throw new BDException("活动信息不存在，请重试");
		}

		if (activity.getType() == ActivityType.PACKAGE.getType()) {
			//产品套装
			if (ActivityMode.PACKAGE_PRODUCT.getType() == activity.getMode()) {
				ProductCentre productCentre = productCentreService.getByKey(activityProduct.getProductId());
				if (null == productCentre) {
					throw new BDException("商品信息不存在，请重试");
				}
				if (activity.getTeamId() == null) {
					activity.setTeamId(productCentre.getLiansuoid());
					activityMapper.updateByPrimaryKeySelective(activity);
				}
				if (activity.getTeamId() != null && productCentre.getLiansuoid() != null) {
					if (activity.getTeamId().longValue() != productCentre.getLiansuoid().longValue()) {
						throw new BDException("单个活动不能添加门店不同的产品");
					}
				}
				//多规格的产品标记
				activityProduct.setHasoption(productCentre.getHasoption());
			}
			//优惠券套装
			else {
				Ticket ticket = ticketService.getByKey(activityProduct.getProductId());
				if (null == ticket) {
					throw new BDException("优惠券信息不存在，请重试");
				}
				//teamID不存在，则直接更新
//                if (activity.getTeamId() == null) {
//                    updateActivity = true;
//                    activity.setTeamId(ticket.getTeamId());
//                }
//                if (activity.getTeamId() != null && activity.getTeamId().longValue() != ticket.getTeamId().longValue()) {
//                    throw new BDException("单个活动不能添加门店不同的优惠券");
//                }
			}
		}

		activityProduct.setCreatetime(new Date());
		int addNum = activityProductMapper.insertSelective(activityProduct);

		//计算活动里面的商品件数
		if (activity.getType() == ActivityType.PACKAGE.getType()) {
			ActivityProductExample example = new ActivityProductExample();
			ActivityProductExample.Criteria criteria = example.createCriteria();
			criteria.andActivityIdEqualTo(activity.getId());
			if (ActivityMode.PACKAGE_PRODUCT.getType() == activity.getMode()) {
				criteria.andTypeEqualTo(ActivityProductType.PACKAGE_PRODUCT.getType());
			} else {
				criteria.andTypeEqualTo(ActivityProductType.PACKAGE_COUPON.getType());
			}
			long productCount = activityProductMapper.countByExample(example);
			if (activity.getJoinNum() == null || activity.getJoinNum().longValue() != productCount) {
				activity.setJoinNum((int) productCount);
			}

			//重新计算修改活动的价格
			changeActivityPrice(activity, true);
		}
		//免单活动，要计算和处理大礼包对应的坐标,用来后续做区域内的数据赛选
		else if (activity.getType() == ActivityType.FREECHARGE.getType()) {
			if (ValidateUtil.isEmptyString(activity.getLatitude()) || ValidateUtil.isEmptyString(activity.getLongitude())) {
				Member shopMember = memberService.getByKey(activityProduct.getProductId());
				if (null != shopMember && ValidateUtil.isNotEmptyString(shopMember.gettLat()) && ValidateUtil.isNotEmptyString(shopMember.gettLng())) {
					activity.setLatitude(shopMember.gettLat());
					activity.setLongitude(shopMember.gettLng());
					activityMapper.updateByPrimaryKey(activity);
				}
			}
		}


		return addNum;
	}

	@Override
	public int editActivityProduct(ActivityProduct activityProduct) {
		int editCount = activityProductMapper.updateByPrimaryKeySelective(activityProduct);
		//修改活动价格
		Activity activity = activityMapper.selectByPrimaryKey(activityProduct.getActivityId());
		//免单活动，要计算和处理大礼包对应的坐标,用来后续做区域内的数据赛选
		if (activity.getType() == ActivityType.FREECHARGE.getType()) {
			if (ValidateUtil.isEmptyString(activity.getLatitude()) || ValidateUtil.isEmptyString(activity.getLongitude())) {
				Member shopMember = memberService.getByKey(activityProduct.getProductId());
				if (null != shopMember && ValidateUtil.isNotEmptyString(shopMember.gettLat()) && ValidateUtil.isNotEmptyString(shopMember.gettLng())) {
					activity.setLatitude(shopMember.gettLat());
					activity.setLongitude(shopMember.gettLng());
					activityMapper.updateByPrimaryKey(activity);
				}
			}
		} else {
			changeActivityPrice(activity, true);
		}
		return editCount;
	}

	@Override
	public int addActivityProductSku(ActivityProductSku activityProductSku) {
		if (activityProductSku.getActivityId() == null) {
			throw new BDException("活动信息异常，请联系系统管理员");
		}
		ProductCentre productCentre = productCentreService.getByKey(activityProductSku.getProductCentreId());
		if (null == productCentre) {
			throw new BDException("商品信息错误，请联系系统管理员");
		}
		Activity activity = activityMapper.selectByPrimaryKey(activityProductSku.getActivityId());
		ActivityProductExample example = new ActivityProductExample();
		example.createCriteria().andProductIdEqualTo(activityProductSku.getProductCentreId()).andActivityIdEqualTo(activityProductSku.getActivityId());
		List<ActivityProduct> activityProductList = activityProductMapper.selectByExample(example);
		ActivityProduct activityProduct = null;
		//一个活动，一个产品，只会有一条记录
		if (ValidateUtil.isNotEmptyCollection(activityProductList)) {
			activityProduct = activityProductList.get(0);
		}
		//活动产品错误，需要重新添加活动产品
		if (null == activityProduct) {
			activityProduct = new ActivityProduct();
			activityProduct.setActivityId(activityProductSku.getActivityId());
			activityProduct.setProductId(activityProductSku.getProductCentreId());
			activityProduct.setProductName(productCentre.getTitle());
			activityProduct.setStock(0);
			activityProduct.setCreatetime(new Date());
			activityProduct.setHasoption(productCentre.getHasoption());
			if (activity.getType() == ActivityType.PACKAGE.getType()) {
				activityProduct.setType(activity.getMode() == ActivityMode.PACKAGE_PRODUCT.getType() ? ActivityProductType.PACKAGE_PRODUCT.getType() : ActivityProductType.PACKAGE_COUPON.getType());
			}
			activityProductMapper.insertSelective(activityProduct);
		}

		activityProductSku.setProductId(activityProduct.getId());
		activityProductSku.setType(activityProduct.getType());
		activityProductSku.setTeamId(productCentre.getLiansuoid());

		int addCount = activityProductSkuMapper.insertSelective(activityProductSku);
		if (addCount > 0) {
			//修改活动商品的价格
			changeActivityProductPrice(activityProduct, true);
			//修改活动的价格
			changeActivityPrice(activity, true);
		}

		return addCount;
	}

	/**
	 * 修改活动商品的价格
	 *
	 * @param activityProduct
	 * @param shouldUpdate
	 */
	private void changeActivityProductPrice(ActivityProduct activityProduct, boolean shouldUpdate) {
		ActivityProduct activityProductPrice = activityProductSkuMapper.selectPriceByActivityIdAndProductId(activityProduct.getActivityId(), activityProduct.getProductId());
		if (null != activityProductPrice) {
			activityProduct.setActivityPrice(activityProductPrice.getActivityPrice());
			activityProduct.setMaxActivityPrice(activityProductPrice.getMaxActivityPrice());
		}
		if (shouldUpdate) {
			activityProductMapper.updateByPrimaryKeySelective(activityProduct);
		}
	}

	@Override
	public int removeActivityProductSku(Long id) {
		if (null == id) {
			throw new BDException("SKU信息异常，请联系系统管理员");
		}
		ActivityProductSku activityProductSku = activityProductSkuMapper.selectByPrimaryKey(id);
		if (null == activityProductSku) {
			throw new BDException("SKU信息异常，请联系系统管理员");
		}
		int removeCount = activityProductSkuMapper.deleteByPrimaryKey(id);
		if (removeCount > 0) {
			//修改活动商品价格
			ActivityProduct activityProduct = activityProductMapper.selectByPrimaryKey(activityProductSku.getProductId());
			changeActivityProductPrice(activityProduct, true);
			//修改活动价格
			Activity activity = activityMapper.selectByPrimaryKey(activityProduct.getActivityId());
			if (null == activity) {
				throw new BDException("活动信息异常，请联系系统管理员");
			}
			changeActivityPrice(activity, true);
		}
		return removeCount;
	}

	@Override
	public JSONObject getActivityDetail(Long memberId, Long activityId) throws IllegalAccessException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Activity activity = activityMapper.selectByPrimaryKey(activityId);
		if (null == activity) {
			throw new BDException("活动信息异常，请重试");
		}
//        resultMap.put("activity", activity);

		//活动产品列表
		ActivityProductExample example = new ActivityProductExample();
		example.createCriteria().andActivityIdEqualTo(activityId);
		List<ActivityProduct> activityProducts = activityProductMapper.selectByExample(example);
		List<ActivityProductVo> activityProductVos = new ArrayList<>();
		resultMap.put("activityProductList", activityProducts);

		ProductCentre detail = new ProductCentre();
		detail.setId(activityId);
		detail.setTitle(activity.getActivityName());
		detail.setMarketprice(activity.getActivityPrice());
		detail.setThumb(activity.getThumb());
		detail.setTimestart(activity.getStartTime());
		detail.setTimeend(activity.getEndTime());
		detail.setProductprice(activity.getActivityPrice());
		detail.setTotal(activity.getStock());
		detail.setDescription(activity.getDescription());
		detail.setProductType(ProductType.Package.getType());

		//优惠套装，优惠券-商品
		if (!(activity.getType() == ActivityType.PACKAGE.getType() && ActivityMode.PACKAGE_COUPON.getType() == activity.getMode())
				&& ValidateUtil.isNotEmptyCollection(activityProducts)) {
			for (ActivityProduct activityProduct : activityProducts) {
				ActivityProductVo activityProductVo = new ActivityProductVo();
				BeanUtils.copyProperties(activityProduct, activityProductVo);
				ActivityProductSkuExample activityProductSkuExample = new ActivityProductSkuExample();
				activityProductSkuExample.createCriteria().andProductIdEqualTo(activityProduct.getId());
				activityProductVo.setActivityProductSkuList(activityProductSkuMapper.selectByExample(activityProductSkuExample));
				activityProductVos.add(activityProductVo);
			}
			resultMap.put("activityProductList", activityProductVos);

			detail.setProductType(ProductType.Package.getType());
		}
		//免单活动
		else if (activity.getType() == ActivityType.FREECHARGE.getType()) {
			detail.setProductType(ProductType.FreeCharge.getType());
			for (ActivityProduct activityProduct : activityProducts) {
				ActivityProductVo activityProductVo = new ActivityProductVo();
				BeanUtils.copyProperties(activityProduct, activityProductVo);
//                ActivityProductSkuExample activityProductSkuExample = new ActivityProductSkuExample();
//                activityProductSkuExample.createCriteria().andProductIdEqualTo(activityProduct.getId());
//                activityProductVo.setActivityProductSkuList(activityProductSkuMapper.selectByExample(activityProductSkuExample));
				activityProductVos.add(activityProductVo);
			}
			resultMap.put("activityProductList", activityProductVos);
		}

		CommanerVo vo = memberService.getCommanderByMembId(memberId);//通过会员Id查询门店信息
		//门店id
		CommanerVo liansuoVo = memberService.getCommanderByMembId(detail.getLiansuoid());//通过会员Id查询门店信息
		if (null != liansuoVo) {
			detail.setLiansuoVo(liansuoVo);
		}

		JSONObject jsonObject = (JSONObject) JSON.toJSON(detail);
		if (vo != null) jsonObject.putAll(ObjectUtils.objectToMap(vo));
		jsonObject.putAll(resultMap);

		return jsonObject;
	}

	@Override
	public List<ActivityProduct> getBuyShops(Long mid) {
		List<ActivityProduct> allUsedProductList = activityProductMapper.getBuyShops(mid);
		if (ValidateUtil.isNotEmptyCollection(allUsedProductList)) {
			//循环查询门店的信息
			for (ActivityProduct activityProduct : allUsedProductList) {
				activityProduct.setShopInfo(memberService.getByKey(activityProduct.getProductId()));
			}
		}
		return allUsedProductList;
	}

	/**
	 * 大礼包通兑券用户下单选择门店
	 */
	@Override
	public List<TicketUsableTeam> getTicketUsableTeam(Long id) {
		List<TicketUsableTeam> ticketUsableTeamList = new ArrayList<>();
		//获取大礼包店铺信息
		List<ActivityProduct> activityProducts = activityProductMapper.selectActivityProductByActivityId(id);
		if (ValidateUtil.isNotEmptyCollection(activityProducts)) {
			for (ActivityProduct activityProduct : activityProducts) {
				List<StoreFreechargeMiddle> storeFreechargeMiddleList = storeFreechargeMiddleMapper.selectByActivityProductId(activityProduct.getId());
				if (ValidateUtil.isEmptyCollection(storeFreechargeMiddleList)) {
					continue;
				}
				List<Long> storeFreechargeIds = new ArrayList();
				storeFreechargeMiddleList.forEach(item -> {
					storeFreechargeIds.add(item.getStoreFreechargeId());
				});
				Map params = new HashedMap();
				params.put("teamId", activityProduct.getProductId());
				params.put("type", 2);
				params.put("storeFreechargeIds", storeFreechargeIds);
				//获取该店铺下面的所有参加活动的商品
				List<StoreFreecharge> storeFreecharges = storeFreechargeMapper.pageListBycondition(params, new RowBounds(0, 1000));
				if (ValidateUtil.isNotEmptyCollection(storeFreecharges)) {
					for (StoreFreecharge storeFreecharge : storeFreecharges) {
						if (storeFreecharge.getType() != null && storeFreecharge.getType() == 2) {
							if (storeFreecharge.getRefId() != null) {
								Ticket ticket = ticketService.getByKey(storeFreecharge.getRefId());
								if (ticket != null && ticket.getUsableFlag() != null && ticket.getUsableFlag() == 1 && ValidateUtil.isNotEmptyString(ticket.getUsableTeam())) {
									TicketUsableTeam ticketUsableTeam = new TicketUsableTeam();
									ticketUsableTeam.setTicketId(ticket.getId());
									ticketUsableTeam.setTicketName(ticket.getTicketName());
									ticketUsableTeam.setTicketImg(ticket.getTicketImg());
									String[] strs = ticket.getUsableTeam().split(",");
									List<Member> list = new ArrayList<>();
									for (String str : strs) {
										Member member = memberService.getByKey(Long.parseLong(str));
										if (member != null) {
											list.add(member);
										}
									}
									ticketUsableTeam.setList(list);
									ticketUsableTeamList.add(ticketUsableTeam);
								}
							}
						}
					}
				}
			}
		}
		return ticketUsableTeamList;
	}

	/**
	 * 前端获取大礼包详情
	 *
	 * @param id
	 * @return
	 */
	@Override
	public Activity getActivityDetailById(Long id) {
		//获取大礼包信息
		Activity activity = activityMapper.selectByPrimaryKey(id);
		List<StoreFreecharge> storeFreechargesTotal = new ArrayList<>();
		//获取大礼包店铺信息
		List<ActivityProduct> activityProducts = activityProductMapper.selectActivityProductByActivityId(id);

		Set<Long> memberIdList = new HashSet<>();
		BigDecimal commissionTotal = BigDecimal.ZERO;
 		//设置有多少家店铺参加活动
		activity.setActivityProductCount(activityProducts.size());
		if (ValidateUtil.isNotEmptyCollection(activityProducts)) {
			for (ActivityProduct activityProduct : activityProducts) {
				int ticketCount = 0;
				BigDecimal ticketSumPrice = BigDecimal.ZERO;
				activityProduct.setShopInfo(memberService.getByKey(activityProduct.getProductId()));
				memberIdList.add(activityProduct.getProductId());
				List<StoreFreechargeMiddle> storeFreechargeMiddleList = storeFreechargeMiddleMapper.selectByActivityProductId(activityProduct.getId());
				if (ValidateUtil.isEmptyCollection(storeFreechargeMiddleList)) {
					continue;
				}
				List<Long> storeFreechargeIds = new ArrayList();
				storeFreechargeMiddleList.forEach(item -> {
					storeFreechargeIds.add(item.getStoreFreechargeId());
				});
				Map params = new HashedMap();
				params.put("teamId", activityProduct.getProductId());
				params.put("type", 2);
				params.put("storeFreechargeIds", storeFreechargeIds);
				//获取该店铺下面的所有参加活动的商品
				List<StoreFreecharge> storeFreecharges = storeFreechargeMapper.pageListBycondition(params, new RowBounds(0, 1000));
				if (ValidateUtil.isNotEmptyCollection(storeFreecharges)) {
					for (StoreFreecharge storeFreecharge : storeFreecharges) {
						if (storeFreecharge.getType() != null && storeFreecharge.getType() == 2) {
							if (storeFreecharge.getRefId() != null) {
								Ticket ticket = ticketService.getByKey(storeFreecharge.getRefId());
								if(ticket != null){
									if (ticket.getUsableFlag() != null && ticket.getUsableFlag() == 1 && ValidateUtil.isNotEmptyString(ticket.getUsableTeam())) {
										String[] strs = ticket.getUsableTeam().split(",");
										for (String str : strs) {
											Member member = memberService.getByKey(Long.parseLong(str));
											if (member != null) {
												memberIdList.add(member.getId());
											}
										}
									}
									LifeConfig lifeConfig = configService.getLifeConfig(activity.getCentreId());
									String shareCommission = "";
									if (activity.getShareCommission() > 0) {
										shareCommission = activity.getShareCommission() + "";
									} else {
										shareCommission = lifeConfig.getShareCommission();
									}
									//计算用户预计分佣
									if (ValidateUtil.isNotEmptyString(shareCommission) && !StringConstans.STR_ZERO.equals(shareCommission)) {
										BigDecimal commission = ticket.getBigGiftAmount().multiply(new BigDecimal(shareCommission)).divide(new BigDecimal(100), 2, RoundingMode.DOWN);
										if (BigDecimal.ZERO.compareTo(commission) < 0) {
											commissionTotal = commissionTotal.add(commission);
										}
									}
								}
							}
						}
					}
				}

				//查询选中的商品
				List<String> list = new ArrayList<>();
				List<StoreFreecharge> storeFreecharges2 = new ArrayList<>();
				if (ValidateUtil.isNotEmptyString(activityProduct.getFreechargeId())) {
					Collections.addAll(list, activityProduct.getFreechargeId().split(","));
					storeFreecharges2 = storeFreechargeMapper.selectByIdInStoreFreecharge(list);
				}
				if (ValidateUtil.isNotEmptyCollection(storeFreecharges2)) {
					for (StoreFreecharge storeFreecharge : storeFreecharges2) {
						ticketSumPrice = ticketSumPrice.add(storeFreecharge.getPrice());
					}
					storeFreechargesTotal.addAll(storeFreecharges2);
				}

				activityProduct.setTicketCount(ticketCount);
				activityProduct.setTicketSumPrice(ticketSumPrice == null ? BigDecimal.ZERO : ticketSumPrice);
				activityProduct.setProductList(storeFreecharges2);
			}
		}

		//售卖数量
//		Integer salesreal = orderMapper.getOrderBYTotal(ProductType.FreeCharge.getType(), activity.getCentreId(), activity.getId());
//		if (salesreal == null) {
//			salesreal = 0;
//		}
		int sold = activity.getSold()==null?0:activity.getSold();
		activity.setSalesreal(sold);
		activity.setStoreFreecharges(storeFreechargesTotal);
		activity.setActivityProducts(activityProducts);

		List<Member> teamList = new ArrayList<>();
		if(ValidateUtil.isNotEmptyCollection(memberIdList)){
			memberIdList.forEach(item ->{
				Member member = memberService.getByKey(item);
				if(member != null){
					teamList.add(member);
				}
			});
		}
		activity.setTeamList(teamList);
		activity.setCommissionTotal(commissionTotal);

		if (null != activity.getDetailsImgList()) {
			String[] list = activity.getDetailsImg().split(",");
			activity.setDetailsImgList(list);
		}

		return activity;
	}

	@Override
	public void deleteAndInsert(Long activityProductId, int type, Long[] ids) {
		storeFreechargeMiddleMapper.deleteByActivityProductIdAndType(activityProductId, type);
		StoreFreechargeMiddle storeFreechargeMiddle = new StoreFreechargeMiddle();
		storeFreechargeMiddle.setActivityProductId(activityProductId);
		storeFreechargeMiddle.setType(type);
		for (int i = 0; i < ids.length; i++) {
			storeFreechargeMiddle.setStoreFreechargeId(ids[i]);
			storeFreechargeMiddleMapper.insertSelective(storeFreechargeMiddle);
		}
	}

	@Override
	public int updateActivity(Activity activity) {
		return activityMapper.updateByPrimaryKeySelective(activity);
	}

	@Override
	public PageUtils<Activity> selectActivityList(Long handselProductAuthorityId, int offset, int limit) {
		PageUtils<Activity> pageUtils = new PageUtils<>();
		int total = activityMapper.countActivityListSize(handselProductAuthorityId);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(activityMapper.selectActivityList(handselProductAuthorityId, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public PageUtils<Activity> selectActivityListByShopProductAuthorityId(Long shopProductAuthorityId, int offset, int limit) {
		PageUtils<Activity> pageUtils = new PageUtils<>();
		int total = activityMapper.countActivityListByShopProductAuthorityId(shopProductAuthorityId);
		if (total > 0) {
			pageUtils.setTotal(total);
			pageUtils.setRows(activityMapper.selectActivityListByShopProductAuthorityId(shopProductAuthorityId, new RowBounds(offset, limit)));
		}
		return pageUtils;
	}

	@Override
	public int changeStock(Integer total, Long activityId) {
		return activityMapper.changeStock(total, activityId);
	}
}
